package com.jianguozh.difs.support.api.framework;

import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
import cloud.tianai.captcha.spring.vo.CaptchaResponse;
import cloud.tianai.captcha.spring.vo.ImageCaptchaVO;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import com.jianguozh.difs.common.bean.R;
import com.jianguozh.difs.framework.annotation.WriteLog;
import com.jianguozh.difs.framework.base.BaseController;
import com.jianguozh.difs.framework.constant.SecurityConstant;
import com.jianguozh.difs.framework.model.LoginInfo;
import com.jianguozh.difs.framework.security.manager.AuthManager;
import com.jianguozh.difs.framework.utils.SpringUtils;
import com.jianguozh.difs.support.api.framework.dto.LoginDto;
import com.jianguozh.difs.support.service.event.LoginSucceedEvent;
import com.jianguozh.difs.support.service.sys.entity.Client;
import com.jianguozh.difs.support.service.sys.service.IClientService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录控制器
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/14 18:05
 */
@RestController
public class LoginController extends BaseController {

    @Autowired
    AuthManager authManager;

    @Autowired
    IClientService clientService;

    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @PostMapping(SecurityConstant.ROUTE_PREFIX_ANON + "/login")
    @WriteLog("用户登录")
    public R<String> login(@RequestBody @Validated LoginDto loginDto) {

        //验证码二次校验
        if (imageCaptchaApplication instanceof SecondaryVerificationApplication) {
            boolean result = ((SecondaryVerificationApplication) imageCaptchaApplication).secondaryVerification(loginDto.getCaptchaId());
            if (!result) {
                return failed("图形验证码校验未通过.");
            }
        }

        Client client = clientService.getByAppId(loginDto.getAppId());
        if (null == client) {
            return failed("appid:" + loginDto.getAppId() + "不存在");
        }
        String clientId = client.getId();
        String token = authManager.authenticate(loginDto.getUsername(), loginDto.getPassword(), clientId);
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(loginDto.getUsername());
        SpringUtils.getApplicationContext().publishEvent(new LoginSucceedEvent(loginInfo));
        return success(token);

    }

    /**
     * 获取客户端应用
     *
     * @param appId
     * @return
     */
    @GetMapping(SecurityConstant.ROUTE_PREFIX_ANON + "/client/{appId}")
    public R<Client> getClient(@PathVariable String appId) {
        Client client = clientService.getByAppId(appId);
        return null != client ? success(client) : R.failed("无此应用.");
    }


    /**
     * 生成验证码
     *
     * @param request
     * @param type
     * @return
     */
    @GetMapping(SecurityConstant.ROUTE_PREFIX_ANON + "/captcha/gen")
    public R<CaptchaResponse<ImageCaptchaVO>> genCaptcha(HttpServletRequest request, @RequestParam(value = "type", required = false) String type) {
        if (StringUtils.isBlank(type)) {
            type = CaptchaTypeConstant.SLIDER;
        }
        CaptchaResponse<ImageCaptchaVO> response = imageCaptchaApplication.generateCaptcha(type);
        return success(response);
    }

    /**
     * 验证验证码
     *
     * @param id
     * @param imageCaptchaTrack
     * @param request
     * @return
     */
    @PostMapping(SecurityConstant.ROUTE_PREFIX_ANON + "/captcha/check/{id}")
    public R<String> checkCaptcha(@PathVariable("id") String id,
                                  @RequestBody ImageCaptchaTrack imageCaptchaTrack,
                                  HttpServletRequest request) {
        try {
            Boolean result = imageCaptchaApplication.matching(id, imageCaptchaTrack);
            return success(result ? "1" : "0");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return failed("校验失败");
    }

}
